package com.example.xiaoxueqixiangmu.jiemian;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.xiaoxueqixiangmu.R;
import com.example.xiaoxueqixiangmu.utils.Constant;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyContact_add extends AppCompatActivity {
    private ListView addPassenger;
    private SimpleAdapter adapter;
    private ProgressDialog progressDialog=null;
    private List<Map<String,Object>> data;

    private Button add;
    private int pos=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_mycontact);

        //添加返回导航
        ActionBar actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        add=(Button)findViewById(R.id.btnSave);
        addPassenger=findViewById(R.id.editListView);
        data=new ArrayList<>();

        final Map<String,Object> map1=new HashMap<>();
        map1.put("key1","姓名");
        map1.put("key3",R.mipmap.forward_25);
        data.add(map1);

        HashMap<String,Object> map2=new HashMap<>();
        map2.put("key1","证件类型");
        map2.put("key3",R.mipmap.forward_25);
        data.add(map2);

        HashMap<String,Object> map3=new HashMap<>();
        map3.put("key1","证件号码");
        map3.put("key3",R.mipmap.forward_25);
        data.add(map3);

        final HashMap<String,Object> map4=new HashMap<>();
        map4.put("key1","乘客类型");
        map4.put("key3",R.mipmap.forward_25);
        data.add(map4);

        final HashMap<String,Object> map5=new HashMap<>();
        map5.put("key1","电话");
        map5.put("key3",R.mipmap.forward_25);
        data.add(map5);

        adapter=new SimpleAdapter(MyContact_add.this,data,R.layout.mylist3,
                new String[]{"key1","key2","key3"},new int[]{R.id.message1,R.id.message2,R.id.edit_icon});
        addPassenger.setAdapter(adapter);

        addPassenger.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                switch (position){
                    case 0://编辑姓名
                        final TextDialog textDialog1=new TextDialog(MyContact_add.this);
                        textDialog1.setIcon(R.mipmap.ic_launcher);
                        textDialog1.setTitle("请输入姓名");
                        textDialog1.show();

                        View textEntryView = textDialog1.getNameDialog();
                        final EditText edit_name1=(EditText) textEntryView.findViewById(R.id.edit_name);
                        Button name_ok1=(Button)textEntryView.findViewById(R.id.name_ok);
                        Button name_cancel1=(Button)textEntryView.findViewById(R.id.name_cancel);
                        name_cancel1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                textDialog1.dismiss();
                            }
                        });
                        name_ok1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String name=edit_name1.getText().toString().trim();
                                data.get(position).put("key2",name);
                                adapter.notifyDataSetChanged();
                                textDialog1.dismiss();
                            }
                        });
                        break;
                    case 1://证件类型
                        final AlertDialog.Builder builder1=new AlertDialog.Builder(MyContact_add.this);
                        builder1.setTitle("请选择证件类型");
                        final String[] items=new String[]{"身份证","学生证","军人证"};
                        final int[] select = {-1};
                        builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String item1=items[which];
                                select[0] = which;
                                Toast.makeText(getApplicationContext(),"您选择的是"+item1,Toast.LENGTH_SHORT).show();
                            }
                        });
                        builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int i) {
                                Map map=data.get(1);
//                                String content= String.valueOf(getResources().getStringArray(select[0]));
                                String content=items[select[0]];
                                map.put("key2",content);
                                data.set(1,map);
                                Intent intent=new Intent();
                                intent.putExtra("row",(Serializable)data.get(position));
                                adapter.notifyDataSetChanged();
                            }
                        });
                        builder1.setNegativeButton("取消",null);
                        builder1.create().show();
                        break;
                    case 2://编辑证件号码
                        final TextDialog textDialog2=new TextDialog(MyContact_add.this);
                        textDialog2.setIcon(R.mipmap.ic_launcher);
                        textDialog2.setTitle("请输入证件号码");
                        textDialog2.show();

                        View textEntryView2 = textDialog2.getNameDialog();
                        final EditText  edt_id=(EditText) textEntryView2.findViewById(R.id.edit_name);
                        Button name_ok2=(Button)textEntryView2.findViewById(R.id.name_ok);
                        Button name_cancel2=(Button)textEntryView2.findViewById(R.id.name_cancel);
                        name_cancel2.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                textDialog2.dismiss();
                            }
                        });
                        name_ok2.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String id1=edt_id.getText().toString().trim();
                                data.get(position).put("key2",id1);
                                adapter.notifyDataSetChanged();
                                textDialog2.dismiss();
                            }
                        });
                        break;
                    case 3://乘客类型
                        AlertDialog.Builder builder2=new AlertDialog.Builder(MyContact_add.this);
                        builder2.setTitle("请选择乘客类型");
                        final String[] item2=new String[]{"成人","儿童","学生","其他"};
                        final int[] select1 = {-1};
                        builder2.setSingleChoiceItems(item2, -1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String item=item2[which];
                                select1[0]=which;
                                Toast.makeText(getApplicationContext(),"您选择的是"+item,Toast.LENGTH_SHORT).show();
                            }
                        });
                        builder2.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Map map=data.get(3);
                                String content=item2[select1[0]];
                                map.put("key2",content);
                                data.set(3,map);
                                Intent intent=new Intent();
                                intent.putExtra("row",(Serializable)data.get(position));
                                adapter.notifyDataSetChanged();
                            }
                        });
                        builder2.setNegativeButton("取消",null);
                        builder2.create().show();
                        break;
                    case 4:
                        final TextDialog textDialog3=new TextDialog(MyContact_add.this);
                        textDialog3.setIcon(R.mipmap.ic_launcher);
                        textDialog3.setTitle("请输入证件号码");
                        textDialog3.show();

                        View textEntryView3 = textDialog3.getNameDialog();
                        final EditText  edt_tel=(EditText) textEntryView3.findViewById(R.id.edit_name);
                        Button name_ok3=(Button)textEntryView3.findViewById(R.id.name_ok);
                        Button name_cancel3=(Button)textEntryView3.findViewById(R.id.name_cancel);
                        name_cancel3.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                textDialog3.dismiss();
                            }
                        });
                        name_ok3.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String id2=edt_tel.getText().toString().trim();
                                data.get(position).put("key2",id2);
                                adapter.notifyDataSetChanged();
                                textDialog3.dismiss();
                            }
                        });
                        break;
                }
            }
        });

        //保存数据
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AddTask().execute();
            }
        });
    }

    private class AddTask extends AsyncTask<String,String,String>{
        @Override
        protected void onPreExecute() {
            //弹出对话框
            progressDialog=ProgressDialog.show(MyContact_add.this,null,"正在加载中...",false,true);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... strings) {
            String result="";
            //读取已经存好的sessionId
            SharedPreferences preferences=MyContact_add.this.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
            String value=preferences.getString("cookie","");
            //获取各个内容
            final String name=data.get(0).get("key2").toString();
            final String idType=data.get(1).get("key2").toString();
            final String id=data.get(2).get("key2").toString();
            final String type=data.get(3).get("key2").toString();
            final String tel=data.get(4).get("key2").toString();

            try{
                OkHttpClient client=new OkHttpClient();
                RequestBody requestBody=new FormBody.Builder()
                        .add("姓名",name)
                        .add("证件类型",idType)
                        .add("证件号码",id)
                        .add("乘客类型",type)
                        .add("电话",tel)
                        .add("action","new")
                        .build();

                Request request=new Request.Builder()
                        .addHeader("Cookie",value)
                        .url(Constant.Host+"/otn/Passenger")
                        .post(requestBody)
                        .build();
                Response response=client.newCall(request).execute();
                result =response.body().string();

            }catch (IOException e){
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (progressDialog!=null){
                progressDialog.dismiss();
            }
            //"1"
            if ("\"1\"".equals(result)){
                Toast.makeText(MyContact_add.this,"添加成功",Toast.LENGTH_SHORT).show();
                MyContact.myContact.finish();
                Intent intent=new Intent();
                intent.setClass(MyContact_add.this,MyContact.class);
                startActivity(intent);
                MyContact_add.this.finish();
            }else if ("\"0\"".equals(result)){
                Toast.makeText(MyContact_add.this, "联系人已存在！", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(MyContact_add.this, "添加失败！", Toast.LENGTH_SHORT)
                        .show();
            }

        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return true;
    }
}
